//
//  DeviceDebugViewController.swift
//  YitihuaPH
//
//  Created by Kai Kang on 2019/1/15.
//  Copyright © 2019 Kai Kang. All rights reserved.
//

import UIKit

class DeviceDebugViewController: UIViewController {

    var dataString = ""
    let btmanager = BlueManager.share
    let orderEncry = SFOrderEncryService.sharedInstance()
    var tableView: UITableView!
    
    var dataSource: [[[String]]] = [[], []]
    var handleBtn: UIButton!
    
    var handleView = DeviceHandleView()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        title = "调试设备"
        view.backgroundColor = .white
        
        handleBtn = UIButton(frame: CGRect.init(x: 0, y: view.bounds.height - 45, width: view.bounds.width, height: 45))
        handleBtn.backgroundColor = UIColor(hex: 0x1fc69e)
        handleBtn.setTitle("操 作", for: .normal)
        handleBtn.addTarget(self, action: #selector(handleViewShow), for: .touchUpInside)
        handleBtn.isEnabled = false
        view.addSubview(handleBtn)
        
        tableView = UITableView.init(frame: CGRect.init(x: 0, y: 0, width: view.bounds.width, height: view.bounds.height - handleBtn.frame.height))
        tableView.delegate = self
        tableView.dataSource = self
        tableView.tableFooterView = UIView()
        tableView.allowsSelection = false
        view.addSubview(tableView)
        
        self.orderEncry.delegate = self
     
        btmanager.didUpdateValue = { [weak self] (chara) in
            if let data = chara.value {
                self?.orderEncry.appendOrder(data)
            }
        }
        
        handleView.selected = { [weak self] (index) in
            self?.handle(index: index)
        }
    }
    
    @objc
    func handleViewShow() {
        handleView.show()
    }
}

extension DeviceDebugViewController: UITableViewDelegate, UITableViewDataSource {
    func numberOfSections(in tableView: UITableView) -> Int {
        return dataSource.count
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return dataSource[section].count
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        var cell = tableView.dequeueReusableCell(withIdentifier: "CELL")
        
        if cell == nil {
            cell = UITableViewCell.init(style: .value1, reuseIdentifier: "CELL")
        }
        
        cell?.textLabel?.text = dataSource[indexPath.section][indexPath.row].first
        cell?.detailTextLabel?.text = dataSource[indexPath.section][indexPath.row].last
        
        return cell!
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return 45
    }
    
    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        return 45
    }
    
    func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        let view = UIView.init(frame: CGRect.init(x: 0, y: 0, width: tableView.frame.size.width, height: 45))
        view.backgroundColor = UIColor.init(white: 0.9, alpha: 1)
        let label = UILabel.init(frame: CGRect.init(x: 0, y: 0, width: view.frame.size.width, height: 45))
        label.font = UIFont.systemFont(ofSize: 15)
        label.text = (section == 0 ? " 设备属性" : " 设备状态")
        view.addSubview(label)
        return view
    }
    
    func showAlert(title: String, msg: String) {
        presentAlertView(withTitle: title, andMsg: msg, andShowCancelAction: false, andConfirmAction: {})
    }
}

extension DeviceDebugViewController: SFOrderEncryServiceDelegate {
    func sfOrderEncryServiceEncryError() {
        
    }
    
    func sfOrderEncryService(_ service: SFOrderEncryService, didEncrydDeviceInfo deviceInfo: [Any], orderType handleType: SFDeviceHandle, deviceState: [Any]) {
        switch handleType {
        case .autoReply:
            if let deviceInfo = deviceInfo as? [[String]], let deviceState = deviceState as? [[String]] {
                dataSource[0] = deviceInfo
                dataSource[1] = deviceState
                tableView.reloadData()
            }
        case .open:
            if let openArr = deviceState as? [String], let open = openArr.first {
                showAlert(title: "开启结果", msg: open == "1" ? "成功" : "失败")
            }
            print(deviceState)
        case .queryIP:
            if let ipArr = deviceState as? [String], let ip = ipArr.first {
                showAlert(title: "设备IP", msg: ip)
            }
        case .configBalanceParam:
            if let balanceArr = deviceState as? [[String]] {
                var balance = ""
                balanceArr.forEach { (item) in
                    balance += String.init(format: "%@:%@\n", item[0], item[1])
                }
                showAlert(title: "平衡参数", msg: balance)
            }
            print(deviceState)
        default:
            print(deviceState)
        }
    }
    
    func sfOrderEncryService(_ service: SFOrderEncryService, isEnd: Bool) {
        print("是否发送结束 \(isEnd)")
        // 直到发送结束后才能操作
        handleBtn.isEnabled = isEnd
    }
    
    func sfOrderEncryService(_ service: SFOrderEncryService, autoReply replyData: Data) {
        btmanager.write(data: replyData)
        print("主动回复")
    }
}

extension DeviceDebugViewController {
    // 设备配置
    func handle(index: NSInteger) {
        switch index {
        case 0:
            configurationDate()
        case 1:
            configIP()
        case 2:
            configBleName()
        case 3:
            configHardwareID()
        case 4:
            queryIP()
        case 5:
            queryDeviceState()
        case 6:
            configBalanceParam()
        case 7:
            initBalanceAngle()
        case 8:
            queryBalanceParam()
        case 9:
            configUploadTimeSep()
        case 10:
            configBleWaiteTimeSep()
        case 11:
            openLock()
        case 12:
            restart()
        default:
            break
        }
    }
    
    func configurationDate() {
        let data = orderEncry.encode(.configTime, param: Date())
        btmanager.write(data: data)
    }
    
    func configIP() {
        let ip = ["192", "168", "100", "15", "5050"]   // 长度5位，最后一位端口号，全部为数字字符串
        let data = orderEncry.encode(.configIP, param: ip)
        btmanager.write(data: data)
    }
    
    func configBleName() {
        let data = orderEncry.encode(.configBlueToothName, param: "sefon lock")
        btmanager.write(data: data)
    }
    
    func configHardwareID() {
        let data = orderEncry.encode(.configHardwareID, param: "aqa111")
        btmanager.write(data: data)
    }
    
    func queryIP() {
        let data = orderEncry.encode(.queryIP, param: "")
        btmanager.write(data: data)
    }
    
    func queryDeviceState() {
        let data = self.orderEncry.encode(.queryState, param: "")
        btmanager.write(data: data)
    }
    
    func configBalanceParam() {
        let param = ["10", "10", "10", "10", "10", "10"] // 参数必须为6位长度的字符串数组，其中字符串只能为数字
        let data = orderEncry.encode(.configBalanceParam, param: param)
        btmanager.write(data: data)
    }
    
    func initBalanceAngle() {
        let data = orderEncry.encode(.initBalanceAngle, param: "")
        btmanager.write(data: data)
    }
    
    func queryBalanceParam() {
        let data = orderEncry.encode(.queryBalanceParam, param: "")
        btmanager.write(data: data)
    }
    
    func configUploadTimeSep() {
        let data = orderEncry.encode(.configUploadTimeSep, param: "10")
        btmanager.write(data: data)
    }
    
    func configBleWaiteTimeSep() {
        let data = orderEncry.encode(.configBlueToothWaitTimeSep, param: "10")
        btmanager.write(data: data)
    }
    
    func openLock() {
        let data = orderEncry.encode(.open, param: "")
        btmanager.write(data: data)
    }
    
    func restart() {
        let data = orderEncry.encode(.reStart, param: "")
        btmanager.write(data: data)
    }
}


/// 弹出一个提示框 AlterView
@discardableResult
func presentAlertView(withTitle title: String,
                      andMsg msg: String,
                      andShowCancelAction showCancelAction: Bool = true,
                      andConfirmText confirmText: String = "确认",
                      andCancelText cancelText: String = "取消",
                      andConfirmAction confirm:@escaping ()->(),
                      andCancelAction cancel:@escaping ()->() = {}) -> UIAlertController {
    let alertView = UIAlertController.init(title: title, message: msg, preferredStyle: .alert)
    alertView.addAction(UIAlertAction.init(title: confirmText, style: .default, handler: { (confirmAction) in
        confirm()
    }))
    if showCancelAction {
        alertView.addAction(UIAlertAction.init(title: cancelText, style: .cancel, handler: { (cancelAction) in
            cancel()
        }))
    }
    UIApplication.shared.keyWindow?.rootViewController?.present(alertView, animated: true, completion: nil)
    return alertView
}
